<template>
  <div>
    <el-container class="config-container">
      <el-aside
        width="220px"
        class="aside"
        style="overflow:hidden; overflow-y:auto; height: 520px;"
      >
        <div class="table-btn">
          <el-button
            icon="el-icon-plus"
            circle
            plain
            size="mini"
            style="margin-left:30px"
            @click="clickAddConfig"
          ></el-button>
          <el-button
            icon="el-icon-edit"
            circle
            plain
            size="mini"
            style="margin-left:30px"
            @click="clickEditConfig"
          ></el-button>

          <el-button
            icon="el-icon-delete"
            circle
            plain
            size="mini"
            style="margin-left:30px"
            @click="deleteConfig(currentId)"
          ></el-button>

          <!-- // 编辑窗口 -->
          <el-dialog
            :title="title"
            :visible.sync="configVisible"
            :modal-append-to-body="false"
            :modal="false"
            width="450px"
            style="margin-top: 100px"
          >
            <el-form inline class="copy-form-inline">
              <el-form-item>
                <el-input
                  v-model="configName"
                  placeholder="名称尽量保持其唯一性，方便识别"
                  size="small"
                  style="width:400px"
                  autocomplete="off"
                >
                  <template slot="prepend">环境变量名称</template>
                </el-input>
              </el-form-item>
            </el-form>

            <div slot="footer" class="edit-footer">
              <el-button @click="configVisible = false" size="small"
                >取 消
              </el-button>
              <el-button type="primary" @click="submitConfig" size="small"
                >确 定
              </el-button>
            </div>
          </el-dialog>

          <br />
        </div>

        <!-- 按钮下面config名称 -->
        <div>
          <div
            v-for="(item, index) in configNameList"
            :key="item.name"
            :name="item.name"
          >
            <el-button
              style="margin-top:10px; margin-right:15px; width:100%; font-size:12px;"
              :dark="item.id == currentId"
              :type="item.id == currentId ? 'primary' : ''"
              @click="clickConfigName(index, item)"
            >
              <span>{{ item.name }}</span>
              <span v-if="item.is_default" style="margin-left:10px;"
                ><i class="el-icon-location-information"></i
              ></span>
            </el-button>
          </div>
        </div>
      </el-aside>

      <!-- // 分割线 -->
      <div class="horizontal-line"></div>
      <!-- // 主体数据 -->
      <el-main>
        <div>
          <el-table
            :data="tableData"
            v-loading="loading"
            border
            style="width: 100%"
            size="mini"
            height="500px"
          >
            <el-table-column label="参数名" width="200">
              <template slot-scope="scope">
                <el-input
                  clearable
                  placeholder="请输入参数名"
                  v-model="scope.row.key"
                  size="mini"
                ></el-input>
              </template>
            </el-table-column>

            <el-table-column label="值">
              <template slot-scope="scope">
                <el-autocomplete
                  style="width:100%"
                  clearable
                  size="mini"
                  class="inline-input"
                  v-model="scope.row.value"
                  :fetch-suggestions="querySearch"
                  placeholder="随机数：${randomInt}"
                  :trigger-on-focus="false"
                ></el-autocomplete>
              </template>
            </el-table-column>
            <el-table-column label="描述" width="180">
              <template slot-scope="scope">
                <el-input
                  clearable
                  v-model="scope.row.desc"
                  size="mini"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template slot-scope="scope">
                <el-button
                  icon="el-icon-circle-plus-outline"
                  size="mini"
                  @click="insertTableRow(scope.$index, scope.row)"
                  style="border:none"
                >
                </el-button>

                <el-button
                  icon="el-icon-delete"
                  size="mini"
                  v-show="scope.$index !== 0"
                  @click="deleteTableRow(scope.$index, scope.row)"
                  style="border:none"
                >
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import {
  addConfig,
  deleteConfig,
  queryConfig,
  updateConfig,
  getParamsAdvice
} from "@/api/config";

export default {
  name: "Config",
  props: {
    loading: {
      required: true,
      type: Boolean
    }
  },
  components: {},
  computed: {},
  watch: {},
  created() {
    this.loadConfig();
    this.loadParamsAdvice();
  },
  data() {
    return {
      restaurants: [],
      configloading: true,
      project_id: parseInt(window.localStorage.getItem("projectId")),
      configForm: {
        variables: [],
        name: "",
        project_id: parseInt(window.localStorage.getItem("projectId"))
      },
      tableData: [{ key: "", value: "", desc: "" }],
      title: "",
      configName: undefined,
      currentId: undefined,
      defaultId: undefined,
      configNameList: [],
      isEdit: false,
      configVisible: false
    };
  },
  methods: {
    // 提交环境变量数据：
    emitConfig() {
      this.$emit("loading", true);
      this.configForm.name = this.configName;
      this.configForm.id = this.currentId;
      this.configForm.variables = this.tableData;
      updateConfig(this.configForm)
        .then(res => {
          if (res.data.code == 200) {
            this.$message({
              message: "保存成功",
              type: "success"
            });
          } else {
            this.$message.error("保存失败:" + res.data.msg);
          }
          this.loadConfig();
        })
        .catch(err => {
          this.$message.error("保存失败：" + err);
          console.log("保存失败：" + err);
        })
        .finally(() => this.$emit("loading", false));
    },

    // 加载环境变量数据
    loadConfig() {
      this.configloading = true;
      queryConfig({
        project_id: parseInt(window.localStorage.getItem("projectId"))
      })
        .then(res => {
          let data = res.data.result;
          if (res.data.code == 200) {
            this.configNameList = data;
            // 获取默认名称
            this.configName = this.configNameList.find(
              ({ is_default }) => is_default === true
            )?.name;
            // 获取默认选中id
            this.currentId = this.configNameList.find(
              ({ is_default }) => is_default === true
            )?.id;

            this.defaultId = this.currentId;

            var tableData = this.configNameList[0].variables;

            this.configloading = false;

            if (tableData.length !== 0) {
              this.tableData = tableData;
            } else {
              this.tableData = [{ key: "", value: "", desc: "" }];
            }
          } else {
            this.$message.error("加载数据失败: " + res.data.msg);
          }
        })
        .catch(err => {
          console.log("错误信息：" + err);
        });
    },

    // 加载右边表格数据
    loadTableData(index, row) {
      queryConfig({
        project_id: parseInt(window.localStorage.getItem("projectId")),
        id: this.currentId
      })
        .then(res => {
          if (index === undefined) {
            row = res.data.result[0];
          }
          if (row["variables"].length !== 0) {
            this.tableData = row["variables"];
          } else {
            this.tableData = [{ key: "", value: "", desc: "" }];
          }
        })
        .catch(err => {
          console.log("错误信息: " + err);
        });
    },

    // 点击左边栏
    clickConfigName(index, row) {
      this.currentId = row.id;
      this.configName = row.name;
      this.loadTableData(index, row);
    },

    clickAddConfig() {
      this.configVisible = true;
      this.title = "新增环境变量";
      this.isEdit = false;
      this.configName = "";
      this.configForm = {
        variables: [],
        name: "",
        project_id: parseInt(window.localStorage.getItem("projectId"))
      };
    },

    clickEditConfig() {
      this.configVisible = true;
      this.isEdit = true;
      this.title = "编辑环境变量";

      this.configForm.id = this.currentId;
      this.configForm.variables = this.tableData;
    },

    // 编辑/新增页面确定按钮事件
    submitConfig() {
      this.configForm.name = this.configName;
      if (!this.isEdit) {
        addConfig(this.configForm)
          .then(res => {
            if (res.data.code === 200) {
              this.$message({
                message: "添加成功",
                type: "success"
              });
            } else {
              this.$message.error(res.data.msg);
            }
            this.loadConfig();
            this.loadTableData();
          })
          .catch(err => {
            this.$message.error("错误消息：" + err);
            console.log("错误消息：" + err);
          });
      } else {
        updateConfig(this.configForm)
          .then(res => {
            if (res.data.code === 200) {
              this.$message({
                message: "更新成功",
                type: "success"
              });
            } else {
              this.$message.error(res.data.msg);
            }
            this.loadConfig();
            this.loadTableData();
          })
          .catch(err => {
            this.$message.error("错误消息：" + err);
            console.log(err);
          });
      }
      this.configVisible = false;
    },

    deleteConfig(id) {
      {
        this.$confirm("此操作将永久删除该记录, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            deleteConfig({ id }).then(res => {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              this.loadConfig();
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除"
            });
          });
      }
    },

    // 表格增加数据方法
    insertTableRow(index, row) {
      this.tableData.push({
        key: "",
        value: "",
        desc: ""
      });
    },

    // 表格删除数据方法
    deleteTableRow(index, row) {
      this.tableData.splice(index, 1);
    },

    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },

    createFilter(queryString) {
      return restaurant => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },

    loadParamsAdvice() {
      getParamsAdvice()
        .then(res => {
          if (res.data.code == 200) {
            this.restaurants = res.data.result;
          } else {
            console.log("加载参数建议失败22");
          }
        })
        .catch(err => {
          console.log("加载参数建议失败" + err);
        });
    }
  }
};
</script>

<style lang="less">
.config-container {
  .aside {
    .table-btn {
      .vertical-line {
        height: 1px;
        border-top: 1px solid #dcdfe6;
        text-align: center;
        width: 132px;
        margin-left: 1px;
      }
    }
  }

  .horizontal-line {
    float: left;
    width: 1px;
    height: 460px;
    background: #dcdfe6;
    margin-left: 10px;
  }
}

.el-button.active {
}
</style>
